﻿using CloudFranceTriple.WebRole.Filters;
using CloudFranceTriple.WebRole.Models;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using Postal; // http://aboutcode.net/postal/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using System.Web.Security;
using WebMatrix.WebData;

namespace CloudFranceTriple.WebRole.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : BaseController
    {
        private CloudFranceTriple.Models.cloudfrAboq2RsDMEntities db = new CloudFranceTriple.Models.cloudfrAboq2RsDMEntities();

        private readonly IWebSecurityWrapper _webSecurity;
        public AccountController()
        {
            this._webSecurity = new WebSecurityWrapper();
        }

        public AccountController(IWebSecurityWrapper webSecurity)
            : base(webSecurity)
        {
            this._webSecurity = webSecurity;
        }       //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            if (returnUrl == null && Request.UrlReferrer != null && Request.UrlReferrer.PathAndQuery != String.Empty)
                returnUrl = Request.UrlReferrer.PathAndQuery.ToLower();

            if (returnUrl == null || returnUrl.StartsWith("/account/")) returnUrl = "/home/index";

            ViewBag.returnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && _webSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                if (returnUrl == null || returnUrl.StartsWith("/account/")) returnUrl = "/home/index";
                return RedirectToLocal(returnUrl);
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", CloudFranceTriple.WebRole.Properties.Resources.AccountLoginFailed);
            return View(model);
        }

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            _webSecurity.Logout();

            return RedirectToAction("Index", "Home", new { area = "" });
        }

        //
        // GET: /Account/Register

        [AllowAnonymous]
        public ActionResult Register()
        {
            var EighteenYearOld = DateTime.Now.AddYears(-18);

            // Mettre 18 ans en limite basse du sélecteur d'année du calendrier JQueryUI
            EighteenYearOld = EighteenYearOld.AddYears(-10);
            ViewBag.TimeZone = new SelectList(GetTimeZoneSelectList(), "Value", "Text", "Romance Standard Time");
            return View(new RegisterModel { Birthday = new DateTime(EighteenYearOld.Year, EighteenYearOld.Month, EighteenYearOld.Day) });
            //return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    var currentIp = Request.UserHostAddress.Substring(0, Request.UserHostAddress.Length > 15 ? 15 : Request.UserHostAddress.Length);
                    var _now = DateTime.UtcNow;
                    var _ForumMessagePostedCounter = db.ForumPostSet.Where(post => post.PostMessage_Author.ToLower() == model.UserName.ToLower()).Count();

                    string confirmationToken = _webSecurity.CreateUserAndAccount(model.UserName, model.Password,
                        new
                        {
                            Email = model.Email,
                            Gravatar = model.Gravatar,
                            TimeZone = model.TimeZone,
                            Location = model.Location,
                            Culture = model.Culture,
                            Theming = model.Theming,
                            Birthday = model.Birthday,
                            UpperLabelSignature = model.UpperLabelSignature,
                            ImageUrlSignature = model.ImageUrlSignature,
                            NavigateUrlSignature = model.NavigateUrlSignature,
                            BottomLabelSignature = model.BottomLabelSignature,
                            ShowInBirthdayList = true,
                            ForumMessagePostedCounter = _ForumMessagePostedCounter,
                            InitialAddressIp = currentIp,
                            LastAddressIp = currentIp,
                            LastRequestDate = _now,
                            ShowInNonAdminList = true
                        }, true);
                    if (confirmationToken != null)
                    {
                        dynamic email = new Email("RegEmail");
                        email.To = model.Email;
                        email.UserName = model.UserName;
                        email.ConfirmationToken = confirmationToken;
                        email.Send();

                        dynamic emailBcc = new Email("RegEmail");
                        emailBcc.To = "postmaster@teamfrancetriple.com";
                        emailBcc.UserName = model.UserName;
                        emailBcc.ConfirmationToken = confirmationToken;
                        emailBcc.Send();
                    }
                    return RedirectToAction("RegisterEmailSent", "Account");

                    //_webSecurity.Login(model.UserName, model.Password);
                    //return RedirectToAction("Index", "Home", new { area = "" });
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [AllowAnonymous]
        public ActionResult RegisterEmailSent()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult RegisterConfirmation(string Id)
        {
            if (_webSecurity.ConfirmAccount(Id))
            {
                return RedirectToAction("RegisterConfirmationSuccess");
            }
            return RedirectToAction("RegisterConfirmationFailure");
        }

        [AllowAnonymous]
        public ActionResult RegisterConfirmationSuccess()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult RegisterConfirmationFailure()
        {
            return View();
        }

        // http://kevin-junghans.blogspot.fr/2013/04/password-reset-with-simplemembership.html
        [AllowAnonymous]
        public ActionResult PasswordRecovery()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult PasswordRecovery(PasswordRecoveryModel model)
        {
            var context = new UsersContext();
            var profile = context.UserProfiles.SingleOrDefault(u => u.UserName == model.UserName);

            if (profile != null)
            {
                string emailAddress = profile.Email;
                if (!string.IsNullOrEmpty(emailAddress))
                {
                    string confirmationToken =
                        _webSecurity.GeneratePasswordResetToken(model.UserName);
                    if (confirmationToken != null)
                    {
                        dynamic email = new Email("PasswordRecoveryEmail");
                        email.To = emailAddress;
                        email.UserName = model.UserName;
                        email.ConfirmationToken = confirmationToken;
                        email.Send();

                        dynamic emailBcc = new Email("PasswordRecoveryEmail");
                        emailBcc.To = "postmaster@teamfrancetriple.com";
                        emailBcc.UserName = model.UserName;
                        emailBcc.ConfirmationToken = confirmationToken;
                        emailBcc.Send();
                    }
                    return RedirectToAction("RegisterEmailSent");
                }
            }
            return RedirectToAction("InvalidUserName");
        }

        [AllowAnonymous]
        public ActionResult InvalidUserName()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult PasswordRecoveryConfirmation(string Id)
        {
            var model = new PasswordRecoveryConfirmModel() { Token = Id };
            return View(model);
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult PasswordRecoveryConfirmation(PasswordRecoveryConfirmModel model)
        {
            if (_webSecurity.ResetPassword(model.Token, model.NewPassword))
            {
                return RedirectToAction("PasswordRecoverySuccess");
            }
            return RedirectToAction("PasswordRecoveryFailure");
        }

        [AllowAnonymous]
        public ActionResult PasswordRecoverySuccess()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult PasswordRecoveryFailure()
        {
            return View();
        }

        //
        // POST: /Account/Disassociate

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId? message = null;

            // Only disassociate the account if the currently logged in user is the owner
            if (ownerAccount == User.Identity.Name)
            {
                // Use a transaction to prevent the user from deleting their last login credential
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.Serializable }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(_webSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return RedirectToAction("Manage", new { Message = message });
        }

        //
        // GET: /Account/Manage

        public ActionResult Manage(ManageMessageId? message)
        {
            var username = User.Identity.Name;
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? CloudFranceTriple.WebRole.Properties.Resources.AccountLoginChangePasswordSuccess
                : message == ManageMessageId.SetPasswordSuccess ? CloudFranceTriple.WebRole.Properties.Resources.AccountLoginSetPasswordSuccess
                : message == ManageMessageId.RemoveLoginSuccess ? CloudFranceTriple.WebRole.Properties.Resources.AccountLoginRemoveLoginSuccess
                : message == ManageMessageId.EditProfileSuccess ? CloudFranceTriple.WebRole.Properties.Resources.AccountUserProfileEditSuccess
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(_webSecurity.GetUserId(username));
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        //
        // POST: /Account/Manage

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(_webSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = _webSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", CloudFranceTriple.WebRole.Properties.Resources.AccountLoginChangePasswordFailed);
                    }
                }
            }
            else
            {
                // User does not have a local password so remove any validation errors caused by a missing
                // OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        _webSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception)
                    {
                        ModelState.AddModelError("", String.Format(CloudFranceTriple.WebRole.Properties.Resources.AccountLoginUserAlreadyExists, User.Identity.Name));
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return PartialView(model);
        }

        public ActionResult UserProfileEdit(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? CloudFranceTriple.WebRole.Properties.Resources.AccountLoginChangePasswordSuccess
                : message == ManageMessageId.SetPasswordSuccess ? CloudFranceTriple.WebRole.Properties.Resources.AccountLoginSetPasswordSuccess
                : message == ManageMessageId.RemoveLoginSuccess ? CloudFranceTriple.WebRole.Properties.Resources.AccountLoginRemoveLoginSuccess
                : message == ManageMessageId.EditProfileSuccess ? CloudFranceTriple.WebRole.Properties.Resources.AccountUserProfileEditSuccess
                 : "";

            var username = User.Identity.Name;
            var currentUserProfile = new UsersContext().UserProfiles.SingleOrDefault(u => u.UserName == username);
            ViewBag.TimeZone = new SelectList(GetTimeZoneSelectList(), "Value", "Text", currentUserProfile.TimeZone);
            return View(currentUserProfile);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UserProfileEdit(UserProfile userProfile)
        {
            if (ModelState.IsValid & userProfile.UserId > 0 && (userProfile.UserId == _webSecurity.CurrentUserId))
            {
                var uc = new UsersContext();
                uc.Entry(userProfile).State = System.Data.EntityState.Modified;
                uc.SaveChanges();
                return RedirectToAction("UserProfileEdit", "Account", new { area = "", Message = ManageMessageId.EditProfileSuccess });
            }

            var username = User.Identity.Name;
            var currentUserProfile = new UsersContext().UserProfiles.SingleOrDefault(u => u.UserName == username);
            return View(currentUserProfile);
        }

        //
        // POST: /Account/ExternalLogin

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }

        //
        // GET: /Account/ExternalLoginCallback

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return RedirectToLocal(returnUrl);
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            }
        }

        //
        // POST: /Account/ExternalLoginConfirmation

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", CloudFranceTriple.WebRole.Properties.Resources.AccountLoginDuplicateUserName);
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }

        //
        // GET: /Account/ExternalLoginFailure

        [AllowAnonymous]
        public ActionResult ExternalLoginFailure()
        {
            return View();
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult ExternalLoginsList(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
        }

        [ChildActionOnly]
        public ActionResult RemoveExternalLogins()
        {
            ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
            List<ExternalLogin> externalLogins = new List<ExternalLogin>();
            foreach (OAuthAccount account in accounts)
            {
                AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);

                externalLogins.Add(new ExternalLogin
                {
                    Provider = account.Provider,
                    ProviderDisplayName = clientData.DisplayName,
                    ProviderUserId = account.ProviderUserId,
                });
            }

            ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(_webSecurity.GetUserId(User.Identity.Name));
            return PartialView("_RemoveExternalLoginsPartial", externalLogins);
        }

        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
            EditProfileSuccess,
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }

            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }

            public override void ExecuteResult(ControllerContext context)
            {
                OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return CloudFranceTriple.WebRole.Properties.Resources.AccountLoginDuplicateUserName;

                case MembershipCreateStatus.DuplicateEmail:
                    return CloudFranceTriple.WebRole.Properties.Resources.AccountLoginDuplicateEmail;

                case MembershipCreateStatus.InvalidPassword:
                    return CloudFranceTriple.WebRole.Properties.Resources.AccountLoginInvalidPassword;

                case MembershipCreateStatus.InvalidEmail:
                    return CloudFranceTriple.WebRole.Properties.Resources.AccountLoginInvalidEmail;

                case MembershipCreateStatus.InvalidAnswer:
                    return CloudFranceTriple.WebRole.Properties.Resources.AccountLoginInvalidAnswer;

                case MembershipCreateStatus.InvalidQuestion:
                    return CloudFranceTriple.WebRole.Properties.Resources.AccountLoginInvalidQuestion;

                case MembershipCreateStatus.InvalidUserName:
                    return CloudFranceTriple.WebRole.Properties.Resources.AccountLoginInvalidUserName;

                case MembershipCreateStatus.ProviderError:
                    return CloudFranceTriple.WebRole.Properties.Resources.AccountLoginProviderError;

                case MembershipCreateStatus.UserRejected:
                    return CloudFranceTriple.WebRole.Properties.Resources.AccountLoginUserRejected;

                default:
                    return CloudFranceTriple.WebRole.Properties.Resources.AccountLoginUnknownError;
            }
        }
        #endregion
    }
}
